package com.colter.project.sample.thread.part06.test1;

import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

//带有延迟元素的线程安全列表 DelayQueue
public class Test5 {
	public static void main(String[] args) {
		DelayQueue<Event5> queue = new DelayQueue<>();
		Thread[] taskThreads = new Thread[5];
		for (int i = 0; i < taskThreads.length; i++) {
			Task5 task = new Task5(i + 1, queue);
			taskThreads[i] = new Thread(task);
		}

		for (int i = 0; i < taskThreads.length; i++) {
			taskThreads[i].start();
		}

		for (int i = 0; i < taskThreads.length; i++) {
			try {
				taskThreads[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		do {
			int counter = 0;
			Event5 event;
			do {
				event = queue.poll();
				if (event != null) {
					counter++;
				}
			} while (event != null);

			System.out.println("You have read:" + new Date() + " " + counter);

			try {
				TimeUnit.MILLISECONDS.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} while (queue.size() > 0);
	}
}

class Event5 implements Delayed {
	private Date startDate;

	public Event5(Date startDate) {
		super();
		this.startDate = startDate;
	}

	@Override
	public int compareTo(Delayed o) {
		long result = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
		if (result < 0) {
			return -1;
		} else if (result > 0) {
			return 1;
		}
		return 0;
	}

	@Override
	public long getDelay(TimeUnit unit) {

		Date now = new Date();
		long diff = startDate.getTime() - now.getTime();
		return unit.convert(diff, TimeUnit.MILLISECONDS);
	}

}

class Task5 implements Runnable {
	private int id;
	private DelayQueue<Event5> queue;

	public Task5(int id, DelayQueue<Event5> queue) {
		super();
		this.id = id;
		this.queue = queue;
	}

	@Override
	public void run() {
		Date now = new Date();
		Date delay = new Date();
		delay.setTime(now.getTime() + (id * 3000));
		System.out.println("Thread:" + id + " delay:" + delay);

		for (int i = 0; i < 100; i++) {
			Event5 event = new Event5(delay);
			queue.add(event);
		}
	}

}
